let BASE_URL = "";
if (process.env.NODE_ENV === "development") {
  // BASE_URL = "http://jjyxkj.w3.luyouxia.net"; //开发环境
  BASE_URL = "http://192.168.1.207:8080"; //开发环境
  // BASE_URL = "/api"; //开发环境
} else {
  BASE_URL = "http://192.168.8.88:8080"; //生产环境
}

const getTokenHandle = () => {
  return uni.getStorageSync("token"); // 获取登录用户token
};
// 请求白名单页面（不需要token请求的页面）
const pageWhiteList = ["pages/login/login"];

// 请求响应拦截处理
const resInterceptHandle = () => {
  const routes = getCurrentPages(); // 获取当前打开过的页面路由数组
  const curRoute = routes[routes.length - 1].route; // 获取当前页面路由
  const flag = pageWhiteList.includes(curRoute);
  if (!flag) {
    // console.log(`---[ ${curRoute} ]页面获取数据需要登录---`);
    uni.redirectTo({
      url: "/pages/login/login",
    });
    uni.removeStorageSync("token");
  }
  return flag;
};

// 请求参数处理
const requestParam = (data, method) => {
  let str = "";
  if (method == "post") {
    str = JSON.stringify(data);
    return str;
  } else if (method == "get") {
    for (let i in data) {
      str += i + "=" + data[i] + "&";
    }
    str = str.length > 0 ? str.substring(0, str.length - 1) : "";
    return encodeURI(str);
  }
};

// 请求封装
const sendRequest = (method = "GET", url = "", params = {}) => {
  let promise = new Promise(async (resolve, reject) => {
    let token = await getTokenHandle();
    const URL = BASE_URL + url + (method === "GET" ? params : "");
    //网络请求
    uni.request({
      header: {
        Authorization: "Bearer " + token,
      },
      url: URL,
      method,
      data: method === "GET" ? {} : params,
      success: function (res) {
        // 响应code 401拦截跳转登录
        if (res.statusCode == 200 && res.data.code === 401) {
          resInterceptHandle();
          return;
        }
        // 服务器返回数据
        if (res.statusCode == 200) {
          resolve(res.data);
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 3000,
            mask: true,
          });
          reject(res);
        }
      },
      fail: function (res) {
        reject(res);
      },
    });
  });
  return promise;
};

// 封装post请求（url:请求接口； data：请求参数；）
const httpPost = async (url, data) => {
  const params = requestParam(data, "post");
  const res = await sendRequest("POST", url, params);
  // console.log("post请求成功响应：", res);
  return res;
};

// 封装get请求（url:请求接口； data：请求参数；）
const httpGet = async (url, data) => {
  let params =
    data && JSON.stringify(data) != "{}" ? "?" + requestParam(data, "get") : "";
  const res = await sendRequest("GET", url, params);
  // console.log("get请求成功响应", res);
  return res;
};

// 封装put请求（url:请求接口； data：请求参数；）
const httpPut = async (url, data) => {
  const res = await sendRequest("PUT", url, data);
  return res;
};

// 自定义请求类型
const http = async (
  params = {
    method: "GET",
    url: "",
    data: {},
  }
) => {
  const res = await sendRequest(params.method, params.url, params.data);
  // console.log(`自定义${params.method}请求成功响应`, res);
  return res;
};

module.exports = {
  Post: httpPost,
  Get: httpGet,
  Put: httpPut,
  http: http,
};
